package com.cc.visitor.service;

import com.cc.alltype.BusinessException;
import com.cc.visitor.dao.LoginQrLogMapper;
import com.cc.visitor.dao.UserWeixinMapper;
import com.cc.visitor.entity.LoginQrLog;
import com.cc.visitor.entity.UserWeixin;
import com.cc.visitor.utils.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author chanchaw
 * @create 2024-12-28 15:23
 */
@Service
public class LoginQrLogServiceImpl implements LoginQrLogService{
    @Autowired
    private LoginQrLogMapper dao;
    @Autowired
    private UserWeixinMapper userWeixinMapper;

    /**
     * 使用登录用二维码的内容 uuid 检测是否有微信用户扫描
     * 有则返回扫描该二维码的微信用户信息，前端拿到数据后进行登录跳转
     * 到主页，同时显示用户信息，例如昵称、姓名等
     * @param uuid
     * @return
     */
    @Override
    public UserWeixin isLogged(String uuid) {
        uuid = Optional.ofNullable(uuid).orElse("");
        if(uuid.length() == 0) throw new BusinessException("没有传入uuid，无法检测是否登录！");
//        List<LoginQrLog> loginQrLogs = dao.selectLoggedIn(uuid);
        List<LoginQrLog> loginQrLogs = dao.select8uuid(uuid);
        if(loginQrLogs == null || loginQrLogs.size() == 0) return null;
        LoginQrLog loginQrLog = Optional.ofNullable(loginQrLogs.get(loginQrLogs.size() - 1)).orElse(new LoginQrLog());

        // 登录UUID有报警msg则抛出异常
        String msg = Optional.ofNullable(loginQrLog.getMsg()).orElse("");
        if(msg.length() > 0) throw new BusinessException(msg);

        String openId = Optional.ofNullable(loginQrLog.getOpenId()).orElse("");
        if(openId.length() == 0) return null;
        UserWeixin userWeixin = userWeixinMapper.get8OpenId(openId);
        if(userWeixin == null) return null;// 新登录页面，还没有用户扫描
        //throw new BusinessException("只有本厂内部员工可以登录，请向管理员索要注册用二维码！");
        Boolean interviewee = SystemUtils.isInterviewee(userWeixin);
        Boolean me = SystemUtils.isMe(userWeixin);
        if(!interviewee && !me) throw new BusinessException("访客身份无法登录，只有本厂人员可以登录系统！");
        return userWeixin;
    }

    @Override
    public int clearMsg(String uuid){
        List<LoginQrLog> loginQrLogs = dao.select8uuid(uuid);
        if(loginQrLogs == null || loginQrLogs.size() == 0) return 0;
        loginQrLogs.forEach(item -> {
            item.setMsg("");
            dao.update(item);
        });
        return loginQrLogs.size();
    }
}
